#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

void SetNonBlock(int fd){
  int f1 = fcntl(fd, F_GETFL);
  if (f1 < 0){
    perror("fcntl");
    return;
  }
  fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
}

int main(){
  SetNonBlock(0);
  while (1){
    char buffer[1024] = {0};
    ssize_t s = read(0, buffer, sizeof(buffer) - 1);
    if (s > 0){
      buffer[s] = 0;
      write(1, buffer, sizeof(buffer) - 1);
      printf("read success, s: %ld, errno: %d\n", s, errno);
    }
    else {
      if (errno == EAGAIN || errno == EWOULDBLOCK){
        printf("数据还未准备好，可以去做做其他事情\n");
        sleep(1);
        continue;
      }
      else {
        printf("read failed, s: %ld, errno: %d\n", s, errno);
        sleep(1);
      }
    }
  }
  return 0;
}
